<?php

namespace mForge\Modules\Cache;

/**
 * Memcache handler.
 */
class MemcacheCacheHandler implements ICacheHandler
{
    /**
     * The lifetime of the cache.
     *
     * @var integer
     */
    protected $lifeTime;

    /**
     * The Memcache object
     *
     * @var Memcache
     */
    protected $memcache;

    /**
     * Whether to store the cache compressed or not.
     *
     * @var boolean
     */
    protected $storeCompressed;

    /**
     *
     * @param array $options
     * @return MemcacheCacheHandler
     */
    public function __construct(array $options)
    {
        $defaults = array(
            'host' => 'localhost',
            'port' => 11211,
            'lifeTime' => 3600,
            'storeCompressed' => false
        );

        $options = \mForge\Utility::arrayOverlay($defaults, $options);

        if (!extension_loaded('memcache')) {
            throw new \RuntimeException('The Memcache PHP extension is not loaded.');
        }
        $this->memcache = new \Memcache();
        $this->memcache->connect($options['host'], $options['port']) or die ("Could not connect");

        $this->lifeTime = (int) $options['lifeTime'];
        $this->storeCompressed = (boolean) $options['storeCompressed'];
        
        return $this;
    }

    /**
     *
     * @param string $id
     * @return MemcacheCacheHandler
     */
    public function clean($id) {
        $this->memcache->delete($id);
        return $this;
    }

    /**
     * 
     *
     * @return MemcacheCacheHandler
     */
    public function cleanAll()
    {
        $this->memcache->flush();
        return $this;
    }
	
    /**
     *
     * @param string $id
     * @return mixed
     */
    public function load($id) {
        return $this->memcache->get($id) ? $this->memcache->get($id) : null;
    }
	
    /**
     *
     *
     * @param string $id
     * @param mixed $data
     */
    public function save($id, $data) {
        if ($this->storeCompressed) {
            $this->memcache->set($id, $data, \MEMCACHE_COMPRESSED, $this->lifeTime);
        } else {
            $this->memcache->set($id, $data, null, $this->lifeTime);
        }
        return $this;
    }
}